package com.tracker;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tracker.util.MasterInformation;
import com.tracker.util.TrackerConnection;



public class Login extends HttpServlet {
	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("login page");
		TrackerConnection traclerConnection = new TrackerConnection();
		HttpSession session = request.getSession();
		String userName = request.getParameter("userid");
		String password = request.getParameter("pword");		
		Connection conn = null;
		Map<String, String> branches = MasterInformation.getBranches();
		try{
			conn = traclerConnection.getConnection();
			PreparedStatement pstmt = conn.prepareStatement("select * from userlogin where userid=? and password = ?");
			pstmt.setString(1, userName);
			pstmt.setString(2, password);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()) {
				PreparedStatement pstmt1 = conn.prepareStatement("select branch from user where userid=?");
				pstmt1.setString(1, userName);
				ResultSet rs1 = pstmt1.executeQuery();
				if(rs1.next()) {
					session.setAttribute("userBranch", branches.get(rs1.getString("branch")));
				}
				
				request.getRequestDispatcher("/home.jsp").forward(request, response);
			} else {
				session.setAttribute("userBranch", "");
				request.getRequestDispatcher("/welcome.jsp").forward(request, response);
			}
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		
		
		
	}

}
